package com.yuma.lock;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

class Window {
    private static int ticket = 100;
    // 1.创建可重入锁
    private static ReentrantLock lock = new ReentrantLock();
    public void sale(){
        // 2.加锁
        lock.lock();  // 锁标识 +1
        if (ticket < 0) {
            lock.unlock();
            return;
        }

        //test(); // 测试重入
        System.out.println(Thread.currentThread().getName() + "正在出售第" + ticket-- + "张票");
        lock.unlock(); // 锁标识 -1
    }

    public void test(){
        lock.lock();  // +2
        System.out.println("测试锁的重入性");
        lock.unlock();  //-1
    }
}

public class ReentrantLockDemo {
    public static void main(String[] args) {
        Window w1 = new Window();
        Window w2 = new Window();
        Window w3 = new Window();

        Thread t1 = new Thread(()->{
            for (int i = 0 ;i < 5; i++){
                w1.sale();
                try {
                    TimeUnit.MICROSECONDS.sleep(200);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }, "A");

        Thread t2 = new Thread(()->{
            for (int i = 0 ;i < 5; i++){
                w2.sale();
                try {
                    TimeUnit.MICROSECONDS.sleep(200);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }, "B");

        Thread t3 = new Thread(()->{
            for (int i = 0 ;i < 5; i++){
                w3.sale();
                try {
                    TimeUnit.MICROSECONDS.sleep(200);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }, "C");
        t1.start();
        t2.start();
        t3.start();
    }
}
